import * as XLSX from "xlsx";

/**
 * 导出 Excel 表格
 * @param title 表头信息
 * @param data 表格体内容
 * @param outFileName 保存的文件名
 */
export const exportExcel = (title: any[], data: any[], outFileName: string) => {
  let prop = "dataIndex";
  title = title.filter((item) => {
    return item.title != "操作";
  });
  let titleList = toolTitleList(title);
  let tableData = [
    [...titleList] //导出表头
  ];

  data.forEach((tableItem, tableIndex) => {
    let rowData: any = [];
    title.forEach((titleItem) => {
      if (titleItem.title === "序号") {
        rowData.push(tableIndex + 1);
      } else {
        rowData.push(tableItem[titleItem[prop]]);
      }
    });
    tableData.push(rowData);
  });

  let aoaToSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, aoaToSheet, outFileName);
  XLSX.writeFile(bookNew, outFileName + ".xls");
};

/**
 * 获取表头信息
 * @param data 传入的表头信息数组
 * @returns
 */
export const toolTitleList = (data) => {
  let result: any = [];
  data.forEach((item: any) => {
    result.push(item["title"]);
  });
  return result;
};

/**
 * 导出案例
 */
const goExport = () => {
  let titleList = [
    {
      title: "序号",
      dataIndex: "index"
    },
    {
      title: "区域名称",
      dataIndex: "area_name"
    },
    {
      title: "厂站名称",
      dataIndex: "st_name"
    }
  ];
  let tableList = [
    {
      area_name: "AREANAME",
      st_name: "STNAME"
    }
  ];
  let outfilename = "数据表"; // 导出的文件名称
  exportExcel(titleList, tableList, outfilename);
};
